﻿using Infrastructure.DbUtility;
using Infrastructure.Utility;
using System;
using System.Data;

public partial class admin_grade : BasePage
{


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Index = 1;
            this.LoadGrade(1, string.Empty);
            if (Request["data"] == "list") this.GetAllGrade();
        }
    }

    private void GetAllGrade()
    {
        string sql = "SELECT * FROM Grade (NOLOCK) WHERE status = 1";
        DbHelper db = new DbHelper();
        var table = db.ExecQueryEx(sql);

        var arr = table.AsEnumerable().Select(r => string.Format("{{\"nid\":{0},\"name\":\"{1}\"}}", r.Value("nid"), r.Value("name")));

        Response.Clear();
        Response.Write("{\"success\": true,\"data\":[" + string.Join(",", arr) + "]}");
        Response.End();
    }

    private void LoadGrade(int index, string keyword)
    {
        string sql = string.Empty;

        string filter = string.IsNullOrWhiteSpace(keyword) ? string.Empty : "[name] LIKE  '%' + {0} + '%'";

        sql = "SELECT COUNT(*) count FROM Grade (NOLOCK) " + (filter == string.Empty ? string.Empty : " WHERE " + filter) + Environment.NewLine;

        if (index == 1) sql += "SELECT TOP " + PAGE_SIZE + " * FROM Grade (NOLOCK)" + (filter == string.Empty ? string.Empty : " WHERE " + filter);
        else sql += "SELECT TOP " + PAGE_SIZE + " * FROM Grade (NOLOCK) WHERE nid NOT IN (SELECT TOP " + ((index - 1) * PAGE_SIZE) + " nid FROM Grade (NOLOCK))" + (filter == string.Empty ? string.Empty : " AND " + filter); ;

        DbHelper db = new DbHelper();
        var ds = db.ExecuteQueryEx(sql, keyword);

        this.Index = index;
        int count = ds.Tables[0].Rows[0].Value<int>("count");
        this.TotalSize = count / PAGE_SIZE + (count % PAGE_SIZE == 0 ? 0 : 1);

        lstGrade.DataSource = ds.Tables[1];
        lstGrade.DataBind();
    }
    protected void btnPost_Click(object sender, EventArgs e)
    {
        var keyword = txtName.Text.Trim();
        this.Index = 1;
        this.LoadGrade(1, keyword);
    }
    protected void btnNavigate_Click(object sender, EventArgs e)
    {
        string sindex = Request["txtGoTo"];
        int index = 0;
        if (!int.TryParse(sindex, out index) || index < 1) return;

        var keyword = txtName.Text.Trim();
        this.Index = index;

        this.LoadGrade(index, keyword);
    }
    protected void btnDel_Click(object sender, EventArgs e)
    {
        var val = Request["selector"];
        if (string.IsNullOrWhiteSpace(val)) return;

        string sql = "DELETE FROM Grade WHERE nid IN (" + val + ")";

        DbHelper db = new DbHelper();
        db.ExecuteUpdate(sql);

        var keyword = txtName.Text.Trim();
        this.LoadGrade(this.Index, keyword);
    }
}